<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { addCourseAPI, getCourseDetailAPI, updateCourseAPI } from '@/pagesOrgan/services/course'
import type { CourseItem } from '@/types/course'
import { onLoad } from '@dcloudio/uni-app'
import { config } from '@/global'
// 表单数据
const formData = ref<CourseItem>({})
// 课程类型列表
const subjectTypeList = ref([
  {
    text: '课程类',
    value: '1',
  },
  {
    text: '课时类',
    value: '2',
  },
])
// 状态列表
const subjectStatusList = ref([
  {
    text: '上架中',
    value: '1',
  },
  {
    text: '已下架',
    value: '0',
  },
])
// 是否是编辑模式
const isEdit = ref(false)
// 课程ID
const courseId = ref(0)
// 加载状态
const isLoading = ref(false)

// 获取路由参数
onLoad((options: any) => {
  // 首次加载数据
  courseId.value = Number(options.id)
  if (courseId.value) {
    isEdit.value = true
    getCourseDetail()
  }
})
// 获取课程详情
const getCourseDetail = async () => {
  isLoading.value = true
  try {
    const res = await getCourseDetailAPI(courseId.value)
    formData.value = res.data
  } catch (error) {
    console.error('获取课程详情失败:', error)
    uni.showToast({ title: '获取课程详情失败', icon: 'none' })
  } finally {
    isLoading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.subjects) {
    uni.showToast({ title: '请输入课程名称', icon: 'none' })
    return
  }
  if (formData.value.subjectPrices === undefined || formData.value.subjectPrices <= 0) {
    uni.showToast({ title: '请输入有效价格', icon: 'none' })
    return
  }
  if (formData.value.classNum === undefined || formData.value.classNum <= 0) {
    uni.showToast({ title: '请输入有效课时', icon: 'none' })
    return
  }
  if (!formData.value.bannerUrl) {
    uni.showToast({ title: '请上传课程图片', icon: 'none' })
    return
  }

  isLoading.value = true
  try {
    if (isEdit.value) {
      await updateCourseAPI(formData.value)
      uni.showToast({ title: '修改成功' })
    } else {
      await addCourseAPI(formData.value)
      uni.showToast({ title: '添加成功' })
    }
    // 通知列表页刷新数据
    uni.$emit('refreshCourseList')
    // 返回列表页
    uni.navigateBack()
  } catch (error) {
    console.error(isEdit.value ? '修改课程失败' : '添加课程失败:', error)
    uni.showToast({ title: isEdit.value ? '修改课程失败' : '添加课程失败', icon: 'none' })
  } finally {
    isLoading.value = false
  }
}

// 上传图片
const uploadImage = () => {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      // 这里应该调用上传文件的API
      // 模拟上传成功
      uploadFile(tempFilePath)
    },
  })
}

// 文件上传-兼容小程序端、H5端、App端
const uploadFile = (file: string) => {
  // 文件上传
  uni.uploadFile({
    url: '/common/upload',
    name: 'file',
    filePath: file,
    success: (res) => {
      if (res.statusCode === 200) {
        console.log(res.data)
        const fileName = JSON.parse(res.data).fileName
        // 个人信息页数据更新
        formData.value.bannerUrl = fileName
        uni.showToast({ icon: 'success', title: '上传成功' })
      } else {
        uni.showToast({ icon: 'error', title: '出现错误' })
      }
    },
  })
}
</script>

<template>
  <view class="course-form-page">
    <view class="form-container">
      <!-- 课程名称 -->
      <view class="form-item">
        <text class="form-label">课程名称</text>
        <input
          type="text"
          v-model="formData.subjects"
          placeholder="请输入课程名称"
          class="form-input"
        />
      </view>

      <!-- 课程价格 -->
      <view class="form-item">
        <text class="form-label">课程价格</text>
        <input
          type="number"
          v-model="formData.subjectPrices"
          placeholder="请输入课程价格"
          class="form-input"
        />
      </view>

      <!-- 课时 -->
      <view class="form-item">
        <text class="form-label">课时</text>
        <input
          type="number"
          v-model="formData.classNum"
          placeholder="请输入课时数量"
          class="form-input"
        />
      </view>

      <!-- 课程图片 -->
      <view class="form-item">
        <text class="form-label">课程图片</text>
        <view class="image-upload">
          <image
            class="preview-image"
            :src="config.baseURL + formData.bannerUrl"
            mode="aspectFill"
          ></image>
          <view class="upload-btn" @click="uploadImage">上传图片</view>
        </view>
      </view>

      <!-- 课程类型 -->
      <view class="form-item">
        <text class="form-label">课程类型</text>
        <view class="radio-group">
          <uni-data-checkbox v-model="formData.subjectType" :localdata="subjectTypeList" />
        </view>
      </view>

      <!-- 状态 -->
      <view class="form-item" v-if="formData.id !== null">
        <text class="form-label">状态</text>
        <view class="radio-group">
          <uni-data-checkbox v-model="formData.subjectStatus" :localdata="subjectStatusList" />
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn" @click="submitForm" :loading="isLoading">
        {{ isEdit ? '修改' : '添加' }}
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.course-form-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.form-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  margin-bottom: 16rpx;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.form-input {
  width: 100%;
  height: 70rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 6rpx;
  box-sizing: border-box;
}

.image-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%; // 确保容器宽度为100%
}

.preview-image {
  width: 100%; // 修改为100%宽度
  height: 300rpx; // 调整高度以保持合适比例
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  object-fit: cover; // 确保图片覆盖整个容器
}

.upload-btn {
  padding: 16rpx 40rpx;
  font-size: 28rpx;
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  border-radius: 6rpx;
}

.radio-group {
  display: flex;
  gap: 40rpx;
  padding: 10rpx 0;
}

.radio {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

.radio radio {
  margin-right: 8rpx;
}

.submit-btn {
  margin-top: 40rpx;
  padding: 20rpx;
  font-size: 32rpx;
  color: #fff;
  background-color: #409eff;
  border-radius: 6rpx;
  text-align: center;
}
</style>
